package com.dream21th.gateway.fliter;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;

public class MD5 {
	public final static String md5(String s){
		char hexDigits[]={
				'0','1','2','3','4','5','6','7','8','9',
				'a','b','c','d','e','f'};
		try{
			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j*2];
			int k=0;
			for(int i=0;i<j;i++){
				byte byte0 = md[i];
				str[k++]=hexDigits[byte0>>>4&0xf];
				str[k++]=hexDigits[byte0&0xf];
			}
			return new String(str);
		}catch(Exception e){
			return null;
		}
	}
	public static String SHA1Encode(String source) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			return byte2String(md.digest(source.getBytes()));
		} catch (Exception ex) {
			throw new RuntimeException("md5 encode error");
		}
	}
	public static String byte2String(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString();
	}

	/**
	 * 返回报文签名处理
	 * @param respJson
	 * @return
	 * @throws UnsupportedEncodingException
	 */
//	public static String respJsonMD5IsCorrect(String respJson) throws UnsupportedEncodingException{
//		String sign=MD5.md5(URLEncoder.encode(respJson, SysConstant.ENCODE_UTF_8)).toUpperCase();
//		JSONObject jsonObject=JSONObject.fromObject(respJson);
//		jsonObject.put("sign", sign);
//		return jsonObject.toString();
//	}

	/**
	 * 返回报文签名处理
	 * @param responseXml
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String respXmlMD5(String responseXml) throws UnsupportedEncodingException{
		String signStr = responseXml.substring(responseXml.indexOf("<sign>"), responseXml.indexOf("</sign>")+7);
		String key = MD5.md5(URLEncoder.encode(responseXml,"utf-8")).toUpperCase();
		//签名
		responseXml = responseXml.replace(signStr,"<sign>"+key+"</sign>");
		return responseXml;
	}
	public static String reqJsonMD5(String reqJson) throws UnsupportedEncodingException{
		String sign=MD5.md5(URLEncoder.encode(reqJson, "utf-8")).toUpperCase();
		return sign;
	}


	public static String reqXmlMD5IsCorrect(String requestXml, String key) {

		String signStr = requestXml.substring(requestXml.indexOf("<sign>"),
				requestXml.indexOf("</sign>") + 7);
		try {
			requestXml = URLEncoder.encode(requestXml.replace(signStr, "<sign>"
					+ key + "</sign>"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		String localSign = MD5.md5(requestXml).toUpperCase();

		String sign = signStr.substring(signStr.indexOf("<sign>") + 6, signStr
				.indexOf("</sign>"));

		if (sign.equals(localSign))
			return localSign;
		else
			return localSign;
	}

}
